package initialize

import (
	"Project/global"
	"Project/model/area"
	req "Project/model/common/request"
	"Project/model/drugs"
	"Project/model/user"
	"Project/service/common"
	adapter "github.com/casbin/gorm-adapter/v3"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"os"
	"strconv"
)

// Gorm 初始化数据库并产生数据库全局变量
// Author SliverHorn
func Gorm() *gorm.DB {
	switch global.GVA_CONFIG.System.DbType {
	case "mysql":
		return GormMysql()
	case "pgsql":
		return GormPgSql()
	default:
		return GormMysql()
	}
}

// RegisterTables 注册数据库表专用
// Author SliverHorn
func RegisterTables(db *gorm.DB) {
	err := db.AutoMigrate(
		//	用户模块表
		user.UserSuper{},
		user.UserArea{},
		user.UserSale{},
		user.Auth{},
		//   药品模块表
		drugs.Drugs{},
		drugs.DrugsRecord{},
		drugs.DrugsMiddle{},
		drugs.DrugsShop{},
		// 区县模块表
		area.Area{},
		//	casbin表
		adapter.CasbinRule{},
	)
	if err != nil {
		global.GVA_LOG.Error("register table failed", zap.Error(err))
		os.Exit(0)
	}
	err = common.UpdateCasbin(strconv.Itoa(int(global.AreaAuth)), req.AreaCasbin())
	err = common.UpdateCasbin(strconv.Itoa(int(global.SuperAuth)), req.SuperCasbin())
	err = common.UpdateCasbin(strconv.Itoa(int(global.ShopAuth)), req.DrugCasbin())
	if err != nil {
		global.GVA_LOG.Error("casbin table failed", zap.Error(err))
		os.Exit(0)
	}
	global.GVA_LOG.Info("register table success")
}
